<template>
  <div>
    <el-form ref="formRef" :model="formData" label-width="120px">
      <el-form-item label="文章标题" prop="title" :error="errors.title">
        <el-input v-model="formData.title"></el-input>
      </el-form-item>
      <el-form-item label="文章分类" prop="column" :error="errors.column">
        <el-select clearable filterable allow-create v-model="formData.column" placeholder="请选择文章分类">
          <el-option v-for="category in categories" :key="category" :label="category" :value="category"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="发表时间" prop="view_date" :error="errors.view_date">
        <el-date-picker v-model="formData.view_date" type="datetime" placeholder="选择日期时间" format="YYYY-MM-DD h:m:s"
          value-format="YYYY-MM-DD h:m:s">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="文章内容" prop="contents_json" :error="errors.contents_json">
        <div class="content-container">
          <div v-for="(content, index) in formData.contents_json" :key="index" class="content-item">
            <div class="content-controls">
              <el-select v-model="content.type" placeholder="选择内容类型" @change="handleContentTypeChange(index)"
                class="type-selector">
                <el-option label="文字" value="text"></el-option>
                <el-option label="图片" value="img"></el-option>
              </el-select>
              <el-button type="danger" size="small" @click="removeContent(index)" class="delete-btn">删除</el-button>
            </div>
            <div class="content-input">
              <el-input v-if="content.type === 'text'" v-model="content.content" type="textarea" placeholder="输入文字内容">
              </el-input>
              <div v-else-if="content.type === 'img'">
                <el-upload
                    class="avatar-uploader"
                    :action="`${baseURL}/image/upload`"
                    :show-file-list="false"
                    :on-success="(res) => handleUploadSuccess(res, index)"
                    :on-error="handleUploadError"
                    :before-upload="beforeUpload">
                    <img v-if="content.url" :src="getImageUrl(content.url)" class="avatar">
                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
                <div class="image-tip">支持 jpg、jpeg、png 格式，大小不超过 500KB</div>
              </div>
            </div>
          </div>
        </div>
        <el-button type="primary" @click="addContent">添加内容</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
        <el-button @click="resetForm(formRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { addArticle, getCategories } from '@/api/article';

// 定义响应式数据
const formRef = ref(null);
const formData = reactive({
  title: '',
  view_date: '',
  contents_json: [
    { type: 'text', content: '' },
  ],
  column: '',
});

const errors = reactive({
  title: '',
  view_date: '',
  contents_json: '',
  column: '',
});

const categories = ref([]);

// 重置表单
const resetForm = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
  formData.contents_json = [{ type: 'text', content: '' }];
  Object.keys(errors).forEach(key => errors[key] = '');
};

// 获取分类数据
const fetchCategories = async () => {
  try {
    const { data } = await getCategories();
    if (data.code === 200) {
      categories.value = data.data;
    } else {
      ElMessage.error(data.message || '获取分类信息失败');
    }
  } catch (error) {
    ElMessage.error('获取分类信息失败：' + error.message);
  }
};

// 校验表单
const validate = () => {
  errors.title = formData.title ? '' : '标题不能为空';
  errors.view_date = formData.view_date ? '' : '发布日期不能为空';
  errors.contents_json = formData.contents_json.length > 0 ? '' : '内容不能为空';
  errors.column = formData.column ? '' : '栏目不能为空';
  return !Object.values(errors).some(error => error);
};

// 提交表单
const handleSubmit = async () => {
  if (!validate()) {
    ElMessage.error('请检查表单填写');
    return;
  }

  try {
    console.log('formData',formData);
    const response = await addArticle(formData);
    ElMessage.success(response.message);
    formRef.value.resetFields();
  } catch (error) {
    ElMessage.error(error.message || '添加文章失败');
  }
};

// 添加内容项
const addContent = () => {
  formData.contents_json.push({ type: 'text', content: '' });
};

// 删除内容项
const removeContent = (index) => {
  ElMessageBox.confirm('确定要删除这个内容项吗？', '提示', {
    type: 'warning',
  }).then(() => {
    formData.contents_json.splice(index, 1);
    ElMessage.success('删除成功');
  }).catch(() => { });
};

// 处理内容类型变化
const handleContentTypeChange = (index) => {
  if (formData.contents_json[index].type === 'img') {
    formData.contents_json[index].url = '';
  } else {
    formData.contents_json[index].content = '';
  }
};

// 处理图片上传成功
const handleUploadSuccess = (res, index) => {
    if (res.code === 200 || res.url) {
        formData.contents_json[index].url = res.url;
        ElMessage.success('图片上传成功');
    } else {
        ElMessage.error(res.error || '上传失败');
    }
};

// 处理图片移除
const handleUploadError = (error) => {
    ElMessage.error('图片上传失败：' + error.message);
};

const beforeUpload = (file) => {
    const isAllowed = ['image/jpeg', 'image/jpg', 'image/png'].includes(file.type);
    const isLt500K = file.size / 1024 < 500;

    if (!isAllowed) {
        ElMessage.error('只能上传 JPG/PNG 格式的图片！');
        return false;
    }
    if (!isLt500K) {
        ElMessage.error('图片大小不能超过 500KB！');
        return false;
    }
    return true;
};

// 生命周期钩子
onMounted(() => {
  fetchCategories();
});
</script>

<style scoped>
/* 新增内容容器样式 */
.content-container {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 20px; /* 内容项间距 */
}

.content-item {
  width: 100%;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
  background: #fff;
  box-sizing: border-box;
}

.content-controls {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.type-selector {
  width: 200px; /* 固定选择器宽度 */
}

.delete-btn {
  margin-left: auto; /* 右对齐按钮 */
}

.content-input {
  margin-top: 10px;
}

/* 调整图片上传组件宽度 */
.el-upload,
:deep(.el-upload-list__item) {
  width: 100%;
}

.el-textarea {
  width: 100%;
}
</style>